package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tanhua.enums.SexEnum;
import com.tanhua.mapper.UserInfoMapper;
import com.tanhua.pojo.User;
import com.tanhua.pojo.UserInfo;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    public Boolean saveUserInfo(Map<String, String> param, String token) {

        //校验token
        User user = userService.queryUserByToken(token);

        if (null == user) {
            return false;
        }

        //如果token正确, 则向userInfo表中添加用户信息
        //解析前端发来的请求参数
            String gender = param.get("gender");
            String nickname = param.get("nickname");
            String birthday = param.get("birthday");
            String city = param.get("city");


            UserInfo userInfo = new UserInfo();
//        userInfo.setSex(StringUtils.endsWithIgnoreCase(gender, "man") ? SexEnum.MAN.getValue() : SexEnum.WOMAN.getValue());
            userInfo.setSex(StringUtils.endsWithIgnoreCase(gender, "man") ? SexEnum.MAN : SexEnum.WOMAN);
            userInfo.setNickName(nickname);
            userInfo.setBirthday(birthday);
            userInfo.setCity(city);
            userInfo.setUserId(user.getId().intValue());
            userInfoMapper.insert(userInfo);

        return true;
    }

    public Boolean saveUserLogo(String token, MultipartFile file) throws IOException {

        //先验证token
        User user = userService.queryUserByToken(token);

        if (null == user){
            return false;
        }

        boolean result = faceEngineService.checkIsPortrait(file.getBytes());
        if (!result){
            return false;
        }

        try {
            PicUploadResult upload = picUploadService.upload(file);
            //将照片信息存入用户信息中
            UserInfo userInfo = new UserInfo();
            userInfo.setLogo(upload.getName());

            LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserInfo::getUserId, user.getId());

            userInfoMapper.update(userInfo, queryWrapper);
        } catch (Exception e) {
            return false;
        }

        return true;
    }
}
